package com.atguigu.gulimall.auth.contorller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ums.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;


    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {

        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","3795582970");
        map.put("client_secret","45aac7044d0bfdb69179ac05685c498d");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);

        //2 处理响应数据
        if (post.getStatusLine().getStatusCode()==200){
            // 获取到数据
            String s = EntityUtils.toString(post.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(s, SocialUserVo.class);

            R r = memberFeignService.oauthLogin(socialUserVo);
            if (r.getCode() == 0) {
                MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
                });

                log.info("微博用户登录成功，用户信息：{}", memberRespVo);
                // 令牌作用域，序列化机制
                // 发卡时候指定域名为父域名

                session.setAttribute(AuthServerConstant.LOGIN_USER,memberRespVo);


                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";

            }
        }
        return "redirect:http://auth.gulimall.com/login.html";

    }
}
